package com.ycsj.goldmedalnewconcept.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.adapter.BirthdayLvAdapter;
import com.ycsj.goldmedalnewconcept.bean.BirthdayInfo;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.UiHelper;
import com.ycsj.goldmedalnewconcept.view.PullToRefreshLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.json.JSONObject;

/**
 * 创建日期：2017/11/15 8:52 描述:生日列表提醒展示 作者:张伟
 */

@SuppressLint("NewApi")
public class BirthdayListActivity extends Activity implements
		View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {

	// 正常请求
	public static final int NORMAL = 0X110;

	// 下拉刷新
	public static final int PULLTOREFRESH = 0X120;

	// 返回
	private LinearLayout llBack;

	// 加载视图
	private LinearLayout llLoading;

	// 空数据
	private LinearLayout llEmpty;

	// 下拉刷新控件
	private PullToRefreshLayout ptrl;

	// 列表控件
	private ListView lv;

	// 头布局
	private View headView;
	// 头布局的布局控件
	private TextView tvNum;

	// 列表控件的数据集合
	private List<BirthdayInfo.ListBean> oldDatas;
	private BirthdayLvAdapter adapter;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_birthday_list);

		// 设置状态栏颜色
		setBar();

		// 初始化View的方法
		initViews();

		// 初始化列表
		initLv();

		// 设置监听
		initListener();

		// 网络请求
		http(NORMAL);

	}

	/**
	 * 初始化View的方法
	 */
	private void initViews() {
		llBack = (LinearLayout) findViewById(R.id.ll_back);
		llLoading = (LinearLayout) findViewById(R.id.ll_loading);
		lv = (ListView) findViewById(R.id.lv);
		llEmpty = (LinearLayout) findViewById(R.id.ll_empty);
		ptrl = (PullToRefreshLayout) findViewById(R.id.refresh_view);
		headView = View.inflate(this, R.layout.lv_birthday_headview, null);
		tvNum = (TextView) headView.findViewById(R.id.tv_num);
	}

	/**
	 * 初始化列表控件的方法
	 */
	private void initLv() {
		oldDatas = new ArrayList<>();
		adapter = new BirthdayLvAdapter(this, oldDatas,
				R.layout.item_lv_birthday_pack);
		// 给ListView添加头布局
		lv.addHeaderView(headView);
	}

	/**
	 * 设置监听的方法
	 */
	private void initListener() {
		llBack.setOnClickListener(this);
		ptrl.setOnRefreshListener(this);
		// 条目点击事件
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {

				new AlertDialog.Builder(BirthdayListActivity.this)
						.setTitle("生日快乐")
						.setMessage("确定发送生日提醒推送吗?")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(
											DialogInterface dialogInterface,
											int i) {
										// 调用服务器后台接口
										//
										http(oldDatas.get(position-1), 1);
//										http(oldDatas.get(position-1), 0);
									}
								}).setNegativeButton("取消", null).show();

			}
		});
	}

	/**
	 * 调用服务器后台推送生日接口
	 *
	 * @param info
	 */
	private void http(BirthdayInfo.ListBean info, int flag) {
		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "32");
		builder.add("alias", info.getUserId() + flag + "");// 0是学生 1是家长
		builder.add("content", getCotent());
		builder.add("title", "生日快乐");
		builder.add("ptype", "0");
		Request request = new Request.Builder()
				.url(Constant.ycsj_count_MessageCenter)
//				.url("http://pm.moregolden.com/ycsj_count/MessageCenter")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Request request, IOException e) {
				runOnUiThread(new Runnable() {
					public void run() {
						 UiHelper.toast(BirthdayListActivity.this, "推送失败");
					}
				});

			}

			@Override
			public void onResponse(Response response) throws IOException {
				try {
					// 请求成功
					// 获取服务器返回的json数据
					String json = response.body().string();
					
					Log.e("test", json);
					if (!TextUtils.isEmpty(json)) {
						JSONObject object = new JSONObject(json);
						if (object.getInt("ResponseCode") == 200) {
							// 表示推送成功
							runOnUiThread(new Runnable() {
								public void run() {
									UiHelper.toast(BirthdayListActivity.this, "推送成功");
								}
							});

						} else {
							// 标识推送失败
							runOnUiThread(new Runnable() {
								public void run() {
//									UiHelper.toast(BirthdayListActivity.this, "推送失败");
								}
							});
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 从字符串集合中随机取一个元素返回
	 */
	private String getCotent() {
		List<String> contents = new ArrayList<>();
		contents.add("愿你像颗种子，勇敢地冲破泥沙，将嫩绿的幼芽伸出地面，指向天空。祝你生日快乐！");
		contents.add("祝你生日快乐，你的善良使这个世界变得更加美好，愿这完全属于你的一天带给你快乐，愿未来的日子锦上添花，学习进步！");
		contents.add("愿你是风，鼓起白色的帆；愿你是船，劈开蓝色的波澜。生活正在你的前方微笑，勇敢地走上前去，将彩色的人生拥抱，生日快乐！");
		contents.add("你长着一对翅膀，坚韧地飞吧，不要为风雨所折服；诚挚地飞吧，不要为香甜的蜜汁所陶醉。朝着明确的目标，飞向美好的人生，生日快乐！");
		contents.add("你长着一对翅膀，坚韧地飞吧，不要为风雨所折服；诚挚地飞吧，不要为香甜的蜜汁所陶醉。朝着明确的目标，飞向美好的人生，生日快乐！");
		contents.add("青春阳光欢笑，为这属于你的日子，舞出欢乐的节拍。祝你生日快乐！");

		Random random = new Random();
		int index = random.nextInt(contents.size() - 1);
		return contents.get(index);
	}

	/**
	 * 网络请求的方法
	 *
	 * @param method
	 */
	private void http(final int method) {
		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "19");
		builder.add("c",
				SPUtil.getString(BirthdayListActivity.this, "account", ""));
		Request request = new Request.Builder()
				.url(Constant.ycsj_count_MessageCenter)
//				.url("http://pm.moregolden.com/ycsj_count/MessageCenter")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Request request, IOException e) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// 请求失败,主线程更新UI操作
						if (llLoading != null) {
							llLoading.setVisibility(View.GONE);
						}
						Toast.makeText(BirthdayListActivity.this, "网络错误",
								Toast.LENGTH_SHORT).show();
					}
				});
			}

			@Override
			public void onResponse(Response response) throws IOException {
				try {
					// 请求成功
					// 获取服务器返回的json数据
					String json = response.body().string();
					if (!TextUtils.isEmpty(json)) {
						final BirthdayInfo info = GsonUtil.jsonToBean(json,
								BirthdayInfo.class);
						// 获取列表数据
						final List<BirthdayInfo.ListBean> newDatas = info
								.getList();
						if (null != newDatas && newDatas.size() != 0) {
							// 证明有列表数据,更新主界面
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									// 设置头部数据
									tvNum.setText(newDatas.size() + "");
									if (method == NORMAL) {
										// 正常请求
										if (llLoading != null) {
											llLoading.setVisibility(View.GONE);
										}
										oldDatas.addAll(newDatas);
										lv.setAdapter(adapter);
									} else {
										// 下拉刷新
										oldDatas.clear();
										oldDatas.addAll(newDatas);
										ptrl.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
										adapter.notifyDataSetChanged();
									}
								}
							});
						} else {
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									// 证明没有数据,显示空视图,隐藏加载框
									if (method == NORMAL) {
										// 正常请求没有数据时设置默认数据
										tvNum.setText("0");
										// 正常加载
										if (llLoading != null) {
											llLoading.setVisibility(View.GONE);
										}
										if (llEmpty != null) {
											llEmpty.setVisibility(View.VISIBLE);
										}
										lv.setAdapter(adapter);
									} else {
										// 下拉刷新
										ptrl.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
									}
								}
							});
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 页面控件的点击事件
	 *
	 * @param view
	 */
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.ll_back:
			// 返回
			finish();
			break;
		}
	}

	/**
	 * 下拉刷新
	 */
	@Override
	public void onRefresh() {
		http(PULLTOREFRESH);
	}

	/**
	 * 设置沉浸状态栏的方法,需要在setContentView()之后调用
	 */
	private void setBar() {
		// 兼容5.0+，状态栏设置透明
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			Window window = getWindow();
			window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.getDecorView().setSystemUiVisibility(
					View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
							| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			window.setStatusBarColor(Color.TRANSPARENT);
		} else
		// 为了沉浸式状态栏 4.4以上才有
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		}
	}

}
